package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description：交友控制层
 * @Author: liulei
 * @Date: 2019年11月01日
 * @Version: V1.0
 **/
@RestController
@CrossOrigin
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserClient userClient;



    /**
     * 添加好友或者添加非好友
     * @param friendid  对方用户ID
     * @param type  1：喜欢 0：不喜欢
     */
    @PutMapping("/like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type){
        //登录验证，并且拿到当前登录用户id
        Claims claims = (Claims) request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        }
        //得到当前登录用户id
        String userid = claims.getId();

        //判断是添加好友还是非好友
        if ("1".equals(type)){
            //添加好友
            int flag = friendService.addFriend(userid, friendid);
            if (flag == 0){
                return new Result(false, StatusCode.ERROR, "不能重复添加好友");
            }
            if (flag == 1){
                userClient.updateFanscountAndFollowcount(userid, friendid, 1);
                return new Result(true, StatusCode.OK, "添加成功");
            }
        }else if ("2".equals(type)){
            //添加非好友
            int flag = friendService.addNoFriend(userid, friendid);
            if (flag == 0){
                return new Result(false, StatusCode.ERROR, "不能重复添加非好友");
            }
            if (flag == 1){
                return new Result(true, StatusCode.OK, "添加成功");
            }
        }
        return new Result(false, StatusCode.ERROR, "参数异常");
    }

    /**
     *  删除好友
     * @param friendid
     * @return
     */
    @DeleteMapping("/{friendid}")
    public Result deleteFriend(@PathVariable String friendid){
        //登录验证，并且拿到当前登录用户id
        Claims claims = (Claims) request.getAttribute("claims_user");
        if (claims == null){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        }
        //得到当前登录用户id
        String userid = claims.getId();
        friendService.deleteFriend(userid, friendid);
        userClient.updateFanscountAndFollowcount(userid, friendid, -1);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
